package io.renren.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.annotation.Login;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.modules.health.dto.HmFoodDTO;
import io.renren.modules.health.dto.HmFoodRecord2DTO;
import io.renren.modules.health.dto.HmFoodRecordDTO;
import io.renren.modules.health.entity.HmFoodRecordEntity;
import io.renren.modules.health.service.HmFoodRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 客户饮食记录
 *
 * @author
 * @since 1.0.0 2024-04-03
 */
@RestController
@RequestMapping("api/hmfoodrecord")
@Api(tags = "客户饮食记录")
public class HmFoodRecordController {
    @Autowired
    private HmFoodRecordService hmFoodRecordService;

    @Login
    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    public Result<PageData<HmFoodRecord2DTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        if (params.get("cusId") != null) params.put("cusId", Long.parseLong((String) params.get("cusId")));
        params.put("recordDate", LocalDate.now());
        if (params.get("planDayTime") != null)
            params.put("planDayTime", Integer.parseInt((String) params.get("planDayTime")));

        PageData<HmFoodRecordDTO> page = hmFoodRecordService.page(params);
        PageData<HmFoodRecord2DTO> hmFoodRecord2DTOPageData = new PageData<HmFoodRecord2DTO>(page.getList().stream().map(f -> {
            HmFoodRecord2DTO hmFoodRecord2DTO = new HmFoodRecord2DTO();
            BeanUtils.copyProperties(f, hmFoodRecord2DTO);
            hmFoodRecord2DTO.setFoods(JSON.parseObject(f.getFoods(), new TypeReference<List<HmFoodDTO>>() {
            }));
            return hmFoodRecord2DTO;
        }).collect(Collectors.toList()), page.getTotal());
        return new Result<PageData<HmFoodRecord2DTO>>().ok(hmFoodRecord2DTOPageData);
    }

    @Login
    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<HmFoodRecordDTO> get(@PathVariable("id") Long id) {
        HmFoodRecordDTO data = hmFoodRecordService.get(id);

        return new Result<HmFoodRecordDTO>().ok(data);
    }

    @Login
    @PostMapping
    @ApiOperation("保存")
    public Result save(@RequestBody HmFoodRecord2DTO dto) {
        dto.setRecordDate(new Date(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toEpochSecond()));
        HashMap<String, Object> param = new HashMap<>();
        param.put("cusId", dto.getCusId());
        param.put("planDayTime", dto.getPlanDayTime());
        param.put("recordDate", LocalDate.now());
        PageData<HmFoodRecordDTO> pageData = hmFoodRecordService.page(param);
        if (pageData.getTotal() > 0) {
            List<HmFoodDTO> foodDTOS = JSON.parseObject(pageData.getList().get(0).getFoods(), new TypeReference<List<HmFoodDTO>>() {
            });
            if (dto.getFoods().get(0).getWeight() == 0) foodDTOS.removeIf(food -> dto.getFoods().get(0).getId().equals(food.getId()));
            else {
                if (foodDTOS.stream().noneMatch(food -> dto.getFoods().get(0).getId().equals(food.getId()))) {
                    foodDTOS.addAll(dto.getFoods());
                } else {
                    foodDTOS.stream()
                            .filter(food -> dto.getFoods().get(0).getId().equals(food.getId()))
                            .findFirst()
                            .get()
                            .setFat(dto.getFoods().get(0).getFat())
                            .setCarbohydrates(dto.getFoods().get(0).getCarbohydrates())
                            .setProtein(dto.getFoods().get(0).getProtein())
                            .setWeight(dto.getFoods().get(0).getWeight())
                            .setFoodTrophy(dto.getFoods().get(0).getFoodTrophy());

                }
            }

            hmFoodRecordService.update(new HmFoodRecordEntity().setFoods(JSON.toJSONString(foodDTOS)),
                    new QueryWrapper<HmFoodRecordEntity>()
                            .eq("cus_id", dto.getCusId())
                            .eq("record_date", LocalDate.now())
                            .eq("plan_day_time", dto.getPlanDayTime()));
        } else {
            hmFoodRecordService.insert(
                    new HmFoodRecordEntity()
                            .setCusId(dto.getCusId())
                            .setFoods(JSON.toJSONString(dto.getFoods()))
                            .setPlanDayTime(dto.getPlanDayTime())
            );

        }

        return new Result();
    }

    @Login
    @DeleteMapping
    @ApiOperation("删除")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        hmFoodRecordService.delete(ids);

        return new Result();
    }

}